<template>
  <RouterView />
</template>

<script setup lang="ts">
import { useWebsocketStore } from '@/stores/modules/websocket';
const intervalId = ref<number>(0);
const isCurrentPage = ref(false); // 是否在应用
const route = useRoute();
onMounted(async () => {
	window.addEventListener('storage', handleAddEventListener);
	window.addEventListener('visibilitychange', handleVisibilityChange);
})
onUnmounted(() => {
	document.removeEventListener('storage', handleAddEventListener);
	document.removeEventListener('visibilitychange', handleVisibilityChange);
	if (intervalId.value) {
		clearInterval(intervalId.value);
		intervalId.value = 0;
	}
})

// 处理页面可见性变化的函数
const handleVisibilityChange = () => {
	const chatList = useWebsocketStore().imStore?.chatList || [];
	if(!chatList.length) return;
	const unreadCount = (chatList?.map((item: { unread: number; }) => { return item?.unread }) || [])?.reduce((pre: number, next: number) => {
		return pre + next;
	});
	const name:string = route.meta.title as string;
	if (document.visibilityState === 'visible') {
		isCurrentPage.value = true;
		// 页面可见，恢复原始标题
		document.title = `Each-${name}`;
		if (intervalId.value) {
			clearInterval(intervalId.value);
			intervalId.value = 0; // 清除后重置为null
		}
	} else {
		isCurrentPage.value = false;
		if(unreadCount > 0 && !intervalId.value){
			setTitle(name);
		}
	}
};
// 设置浏览器标题
const setTitle = (name: any) => {
	if (intervalId.value) {
		clearInterval(intervalId.value);
		intervalId.value = 0;
	}
	// 设置定时器，每隔 800 毫秒执行一次回调函数
	const titleList = ['您有未读消息', `Each-${name}`];
	let index = 0;
	intervalId.value = setInterval(() => {
		document.title = titleList[index];
		index = (index + 1) % titleList.length;
	}, 800);
}
// 收到的消息-处理
const handleAddEventListener = (event: any) => {
    const websocketMsg = event.target.localStorage.websocketMsg;
    if(websocketMsg){
		const newValue = JSON.parse(websocketMsg);
        const data = JSON.parse(newValue?.v).content; // 文本信息
        const extraInfo = JSON.parse(newValue?.v)?.extraInfo; // 文件列表
		let body = null;
		if(extraInfo?.ext){
			body = '[文件]';
		}else{
			body = data?.includes('<img') ? data?.replace(/<img.*?>/g, "[图片]").replace(/<[^>]*>/g,' ') : data?.replace(/<[^>]*>/g, '');
		}
		// console.log('body===', body);
		handleVisibilityChange();
		if(isCurrentPage.value){
			useWebsocketStore().sendNotification(body);
		}
    }
}
</script>
